/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: zy
 * @Date: 2021-10-21 09:21:43
 * @Last Modified by:   lt
 * @Last Modified time: 2021-10-27 15:37:14
 */

import React, { useEffect, useState } from 'react';
import { Modal, Button, Space, Input, Form, TreeSelect, message } from 'antd';
import { checkIsbn, saveBook } from '@/services/book';
import type { BookInfoType, BookTypeItem } from '@/services/book';

type PropsType = {
  operation: number;
  modifyAid: number;
  modalVisible: boolean;
  hideModal: () => void;
  completeOperation: () => void;
  dataSource: BookInfoType | undefined;
  treeData: BookTypeItem[] | [];
};

type formatDataType = {
  value: number;
  title: string;
  children: formatDataType[] | [];
};
const BookUpdateModal = ({
  operation,
  modifyAid,
  modalVisible,
  hideModal,
  completeOperation,
  dataSource,
  treeData,
}: PropsType) => {
  const [form] = Form.useForm(); // 表单对象
  const [modalTitle, setModalTitle] = useState('新增'); //设置modal标题
  const [isDisable, setIsDisable] = useState(false); //设置提交按钮是否可用
  const [loading, setLoading] = useState(false); //设置确认按钮的loading
  const Layout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } }; //表单格式

  /**
   * @description: 表单初始化(1、渲染modal数据；2、判断modal标题)
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      if (operation === 1) {
        if (dataSource) {
          const { isbn, name, quantity, remarks, typeAid, typeName } = dataSource;
          form.setFieldsValue({
            name,
            isbn,
            quantity,
            remarks,
            type: { label: typeName, value: typeAid },
          });
        }
      } else {
        form.resetFields();
      }
      setModalTitle(operation === 0 ? '新增图书' : '修改图书');
    }
    return function cleanup() {
      mounted = false;
    };
  }, [operation, modifyAid]);

  /**
   * @description: treeData数据格式化(将传入的treedata转换成树形结构的数据)
   */
  const handleData = (data: BookTypeItem[] | []) => {
    const item: formatDataType[] = [];
    data.map((list) => {
      const newData: formatDataType = {
        value: 0,
        title: '',
        children: [],
      };
      newData.value = list.aid;
      newData.title = list.name;
      if (list.name) newData.children = list.children ? handleData(list.children) : []; // 如果还有子集，就再次调用自己
      item.push(newData);
    });
    return item;
  };

  /**
   * @description: 校验isbn（1、传入数据通过接口传给后端；
   *                        2、根据返回的数据判别是否存在和数据是否渲染
   *                        3、信息提示）
   */
  const checkISBN = async (event: any) => {
    const params = { aid: modifyAid, isbn: event.target.value };
    const msg = await checkIsbn(params);
    if (msg?.code === 10000) {
      const { isExist } = msg.data;
      if (isExist) {
        if (operation === 0) {
          const bookInfo = msg.data.bookInfo;
          const { isbn, name, quantity, remarks, typeAid, typeName } = bookInfo;
          form.setFieldsValue({
            name,
            isbn,
            quantity,
            remarks,
            type: { label: typeName, value: typeAid },
          });
        }
        setIsDisable(true);
        message.error('ISBN号已存在，请修改！');
      } else {
        setIsDisable(false);
      }
    } else {
      message.error(msg ? msg.message : '校验失败');
    }
  };

  /**
   * @description: 关闭modal并清空表单数据
   */
  const onCancel = () => {
    if (operation !== 1) {
      //非修改时重置form
      form.resetFields();
    }
    hideModal();
  };

  /**
   * @description: 表单提交(传入数据，调用接口保存表单数据并做信息提示)
   */
  const finishHandler = async (formData: any) => {
    setLoading(true);
    const { name, isbn, quantity, remarks, type } = formData;
    const params = {
      aid: modifyAid,
      name,
      isbn,
      quantity,
      remarks,
      typeAid: type.value,
    };
    const msg = await saveBook(params);
    if (msg?.code === 10000) {
      setTimeout(() => {
        message.success('提交成功');
        hideModal();
        form.resetFields();
        completeOperation();
        setLoading(false);
      }, 200);
    } else {
      message.error(msg ? msg.message : '提交失败');
    }
  };

  return (
    <div>
      <Modal
        forceRender
        width={649}
        title={modalTitle}
        visible={modalVisible}
        onCancel={onCancel}
        footer={
          <Space>
            <Button onClick={onCancel}>取消</Button>
            <Button
              type="primary"
              disabled={isDisable}
              loading={loading}
              onClick={() => form.submit()}
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form {...Layout} layout="horizontal" form={form} onFinish={finishHandler}>
          <Form.Item
            name="name"
            key="name"
            label="名称："
            rules={[
              { required: true, message: '请输入名称' },
              { max: 32, type: 'string', message: '图书名称最长为32个字符' },
            ]}
          >
            <Input placeholder="请输入" allowClear={true} />
          </Form.Item>
          <Form.Item
            name="isbn"
            key="isbn"
            label="ISBN号："
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入ISBN号' },
              { len: 17, message: 'isbn号为17位字符' },
            ]}
          >
            <Input placeholder="请输入" allowClear={true} key="isbn" onBlur={(e) => checkISBN(e)} />
          </Form.Item>
          <Form.Item
            name="type"
            key="type"
            label="图书类型："
            rules={[{ required: true, message: '请选择图书类型' }]}
          >
            <TreeSelect
              allowClear
              placeholder="请选择"
              treeData={handleData(treeData)}
              labelInValue={true}
            />
          </Form.Item>
          <Form.Item
            name="quantity"
            key="quantity"
            label="数量："
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入数量' },
              { pattern: new RegExp(/^\+?[1-9][0-9]*$/, 'g'), message: '数量为非0正整数' },
            ]}
          >
            <Input type="number" placeholder="请输入" allowClear={true} key="quantity" />
          </Form.Item>
          <Form.Item name="remarks" key="remarks" label="备注">
            <Input.TextArea name="remark" showCount={true} maxLength={100} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BookUpdateModal;
